package v1

import (
	"sweetsunnyflower/app/models/photo"
	"sweetsunnyflower/app/policies"
	"sweetsunnyflower/app/requests"
	"sweetsunnyflower/pkg/response"

	"github.com/gin-gonic/gin"
)

type PhotosController struct {
	Controller
}

func (ctrl *PhotosController) Index(c *gin.Context) {
	photos := photo.All()
	response.Data(c, photos)
}

func (ctrl *PhotosController) Show(c *gin.Context) {
	photoModel := photo.Get(c.Param("id"))
	if photoModel.ID == 0 {
		response.Abort404(c)
		return
	}
	response.Data(c, photoModel)
}

func (ctrl *PhotosController) Store(c *gin.Context) {

	request := requests.PhotoRequest{}
	if ok := requests.Validate(c, &request, requests.PhotoSave); !ok {
		return
	}

	photoModel := photo.Photo{
		Name:      request.Name,
		OriginURL: request.OriginURL,
	}
	photoModel.Create()
	if photoModel.ID > 0 {
		response.Created(c, photoModel)
	} else {
		response.Abort500(c, "创建失败，请稍后尝试~")
	}
}

func (ctrl *PhotosController) Update(c *gin.Context) {

	photoModel := photo.Get(c.Param("id"))
	if photoModel.ID == 0 {
		response.Abort404(c)
		return
	}

	if ok := policies.CanModifyPhoto(c, photoModel); !ok {
		response.Abort403(c)
		return
	}

	t := c.Param("type")

	if t == "ps" {
		request := requests.PhotoPSRequest{}
		if ok := requests.Validate(c, &request, requests.PhotoPSSave); !ok {
			return
		}

		photoModel.PsURL = request.PsURL

		rowsAffected := photoModel.Save()
		if rowsAffected > 0 {
			response.Data(c, photoModel)
		} else {
			response.Abort500(c, "更新失败，请稍后尝试~")
		}
	} else if t == "remark" {
		request := requests.PhotoRemarkRequest{}
		if ok := requests.Validate(c, &request, requests.PhotoRemarkSave); !ok {
			return
		}
		photoModel.Remark = request.Remark
		rowsAffected := photoModel.Save()
		if rowsAffected > 0 {
			response.Data(c, photoModel)
		} else {
			response.Abort500(c, "更新失败，请稍后尝试~")
		}
	} else {
		request := requests.PhotoDemoRequest{}
		if ok := requests.Validate(c, &request, requests.PhotoDemoSave); !ok {
			return
		}
		photoModel.DemoURL = request.DemoURL

		rowsAffected := photoModel.Save()
		if rowsAffected > 0 {
			response.Data(c, photoModel)
		} else {
			response.Abort500(c, "更新失败，请稍后尝试~")
		}
	}
}

func (ctrl *PhotosController) Delete(c *gin.Context) {

	photoModel := photo.Get(c.Param("id"))
	if photoModel.ID == 0 {
		response.Abort404(c)
		return
	}

	if ok := policies.CanModifyPhoto(c, photoModel); !ok {
		response.Abort403(c)
		return
	}

	rowsAffected := photoModel.Delete()
	if rowsAffected > 0 {
		response.Success(c)
		return
	}

	response.Abort500(c, "删除失败，请稍后尝试~")
}
